<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">需求提报</span>
      </template>
      <template #default>
        <el-form
          :ref="(el: any) => (searchFormRef = el)"
          :model="searchForm"
          label-width="100px"
          class="form_search"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in CheckSearch"
              v-bind="colLayout"
              :key="i"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  class="width_100"
                  :multiple="item.multiple"
                  v-model="searchForm[item.prop]"
                  :options="selectOptions(item.prop)"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabInputForm
                  class="width_100"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabTimeForm
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'lazySelect'"
                :label="item.label"
                :prop="item.prop"
              >
                <LazySelect
                  class="width_100"
                  pageType="2"
                  type="product_code"
                  :multiple="item.multiple"
                  v-model="searchForm[item.prop]"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'range'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabRangeForm
                  :ref="(el) => (vabRangeFormRef = el)"
                  v-model="searchForm[item.prop]"
                />
              </el-form-item>
            </el-col>
            <!-- 按钮 -->
            <el-col v-bind="colBtn">
              <div class="flex_just_end">
                <el-button size="small" type="primary" @click="handleSearch()">
                  查询
                </el-button>
                <el-button size="small" @click="resetForm(searchFormRef)">
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <vab-card shadow="always">
      <template #header>
        <div class="flex_sb">
          <span class="leve2_title">需求明细</span>
          <div class="flex_just_end" style="padding-top: 4px">
            <VabAuthButton title="取消" @click="handleClick('close')" />
            <VabAuthButton update title="复制" @click="handleClick('copy')" />
            <VabAuthButton
              type="primary"
              title="新建"
              @click="handleClick('create')"
            />
          </div>
        </div>
      </template>
      <el-table
        border
        height="430"
        style="width: 100%"
        :data="data.dataSource"
        v-loading="data.loading"
      >
        <el-table-column align="center" width="40" fixed="left">
          <template #default="{ row, $index }">
            <label
              class="el-checkbox"
              :class="{ 'is-checked': radioKey == row.id }"
              @click="handleCurrentChange(row)"
            >
              <span
                class="el-checkbox__input"
                :class="{ 'is-checked': radioKey == row.id }"
              >
                <span class="el-checkbox__inner"></span>
              </span>
            </label>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span
              class="ellipsis"
              v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
            ></span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :min-width="item.width || 180"
          :prop="item.prop"
          :label="item.label"
          :align="
            item.type == 'money' || item.type == 'number' ? 'right' : 'center'
          "
        >
          <template #header>
            <span class="text_center">{{ item.label }}</span>
          </template>
          <template #default="{ row }">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span v-if="item.prop == 'status'" class="tagStatus">
                <el-tag :type="statusColor(row.status)">
                  {{ row.status_str || '--' }}
                </el-tag>
              </span>
              <span class="ellipsis" v-if="item.prop == 'shipping_address'">
                {{ row.shipping_address || '' }} {{ row.address || '' }}
              </span>
              <span
                v-if="item.prop == 'order_no'"
                class="ellipsis link"
                @click="router.push('/procure/detail?order_no=' + row.order_no)"
              >
                {{ row.order_no || '--' }}
              </span>
            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ _FieldFormat(row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="{ row }">
            <VabAuthButton
              type="primary"
              title="去处理"
              v-if="row.status == '0'"
              @click="handleClick('toHandle', row)"
            />
            <VabAuthButton
              type="primary"
              title="查看详情"
              v-if="row.status != '0'"
              @click="router.push('/procure/detail?order_no=' + row.order_no)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
    </vab-card>
  </div>
</template>
<!-- 库存查询 -->
<script lang="ts" setup>
  defineOptions({
    name: 'ProcureCheck',
  })
  /**
   * @import
   */
  import {
    CheckUserAuth,
    DateFormat,
    FieldFormat,
    StrShift,
  } from '~/src/utils/utils'
  import { ElMessageBox, FormInstance } from 'element-plus'
  import {
    CheckCloums,
    CheckSearch,
    OtherOutSearchSelect,
  } from './components/tools'
  import {
    customerOrderList,
    customerOrderUpdateStatus,
    getSearchBase,
  } from '~/src/api/dms/customerOrder'
  import LazySelect from '/@/components/lazySelect/index.vue'
  import { getCustomerCategoryList } from '~/src/api/dms/home/homeCustomer'
  /**
   * @var
   */
  const colLayout = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 8,
    xl: 6,
  }
  const colBtn = {
    xs: 24,
    sm: 12,
    md: 12,
    lg: 24,
    xl: 12,
  }
  const proxy: any = getCurrentInstance()?.proxy
  const router = useRouter()
  const route: any = useRoute()

  const searchFormRef = ref<any>(null)
  const searchForm = reactive<any>({})
  const vabRangeFormRef = ref<any>()
  const data = reactive<any>({
    dataSource: [],
    cloums: [],
    pageNum: 1,
    pageSize: 20,
    count: 0,
  })
  data.dataSource = []
  data.cloums = CheckCloums

  const screenOptions = reactive<any>({
    categoryList: [],
  })
  let isCheck = ref(false)
  // 需求占有弹窗
  const currentRow = ref<any>(null) //选中块
  const radioKey = ref<any>(-1) //唯一值

  /**
   * @method
   */
  const handleSearch = async (value = '') => {
    isCheck.value = true
    await _GetProductList()
    proxy.$Message('查询成功', 'success')
  }
  // 重置
  const resetForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    isCheck.value = false
    radioKey.value = -1
    currentRow.value = null
    await vabRangeFormRef.value.reset()
    await formEl.resetFields()
    await _GetProductList()
    proxy.$Message('重置成功', 'success')
  }
  // 回车
  const onkeydown = (value: any) => {
    isCheck.value = true
    _GetProductList()
  }

  // 单选
  const handleCurrentChange = (row: any) => {
    if (row.id == radioKey.value) {
      radioKey.value = -1
      currentRow.value = null
      return
    }
    radioKey.value = row.id
    currentRow.value = row
  }
  // 页码
  const handlePageNum = (value: any) => {
    data.pageNum = value
    _GetProductList()
  }
  // 页数
  const handlePageSize = (value: any) => {
    data.pageSize = value
    _GetProductList()
  }

  // 点击事件
  const handleClick = (value: any, row: any = {}) => {
    // 新建
    if (value == 'create') {
      router.push({
        path: '/procure/create',
        query: {
          order_no: '',
          from_type: value,
        },
      })
      return
    }

    // 去处理
    if (value == 'toHandle') {
      router.push({
        path: '/procure/create',
        query: {
          order_no: row.order_no,
          from_type: value,
        },
      })
      return
    }
    if (!currentRow.value) {
      proxy.$Message('请选择需要操作的需求！', 'warning')
      return
    }
    const { order_no, status } = currentRow.value

    // 取消
    if (value == 'close') {
      if (status != '0' && status != '1') {
        proxy.$Message('该需求不可被操作!', 'warning')
        return
      }

      ElMessageBox.confirm('该需求是否确定取消', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          customerOrderUpdateStatus({ order_no, status: '2' }).then((res) => {
            proxy.$Message('取消成功', 'success')
            radioKey.value = -1
            currentRow.value = null
            _GetProductList()
          })
        })
        .catch(() => {})
      return
    }
    // 复制
    if (value == 'copy') {
      router.push({
        path: '/procure/create',
        query: {
          order_no,
          from_type: value,
        },
      })
      return
    }
  }
  // 筛选项格式化
  const selectOptions = (value: string) => {
    if (!screenOptions && !value) return
    return OtherOutSearchSelect(value, screenOptions)
  }
  // 字段级格式化
  const _FieldFormat = (value: string, type = '') => {
    if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
    return FieldFormat(value, type)
  }

  // 生效状态tag_color
  const statusColor = (value: number) => {
    if (value == 0) return 'warning'
    if (value == 1) return 'success'
    if (value == 2) return 'danger'
    return 'info'
  }

  // 筛选项
  const _GetScreenOptions = async () => {
    const cateRes = await getCustomerCategoryList() //买方
    const createRes = await getSearchBase() //创建人

    screenOptions.categoryList = cateRes.data
    screenOptions.creator = createRes.data.creator
  }
  // 获取数据
  const _GetProductList = async () => {
    data.loading = true

    let _searchForm: any = { ...searchForm }
    // 解构区间
    let vStart = ''
    let vEnd = ''
    if (vabRangeFormRef.value) {
      vStart = vabRangeFormRef.value.vStart
      vEnd = vabRangeFormRef.value.vEnd
    }

    if (!isCheck.value) {
      _searchForm = {}
      vStart = ''
      vEnd = ''
    }

    const create_time = _searchForm?.create_time

    let query = {
      status: _searchForm?.status ? StrShift(_searchForm?.status) : '',
      product_code: _searchForm?.product_code
        ? StrShift(_searchForm?.product_code)
        : '',
      start_time: create_time ? DateFormat(create_time[0]) : '',
      end_time: create_time ? DateFormat(create_time[1]) : '',
      order_no: _searchForm?.order_no || '',
      buyer_customer_id: _searchForm?.buyer_customer_id
        ? StrShift(_searchForm?.buyer_customer_id)
        : '',
      create_user_id: _searchForm?.create_user_id
        ? StrShift(_searchForm?.create_user_id)
        : '',
      sales_num_start: vStart ? `${vStart}` : '',
      sales_num_end: vEnd ? `${vEnd}` : '',
      page: data.pageNum,
      pagesize: data.pageSize,
    }

    try {
      let res = await customerOrderList({ ...query })
      data.dataSource = res.data.list
      data.count = res.data.count
      data.loading = false
    } catch (error) {}
  }
  onMounted(() => {
    _GetProductList()
    _GetScreenOptions()
  })
</script>

<style lang="scss" scoped>
  @import '../../components/public.scss';

  .tagStatus {
    :deep() {
      .el-tag {
        width: 56px !important;
      }
    }
  }
</style>
